package com.geekcoding.geekoj.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.geekcoding.geekoj.entity.UserEntity;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.NonNull;

import javax.crypto.SecretKey;
import java.util.Map;

public class JWTUtils {

    private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SIGNATURE_ALGORITHM);

    private static final byte[] KEY = "xiaobai".getBytes();

    private static final long EXPIRE_MILLIS = 24 * 60 * 60 * 1000;

    public static String createJWT(String userId, String userName) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("userId", userId);
        map.put("userName", userName);
        return JWTUtil.createToken(map, KEY);
    }

    public static String creatJWT(@NonNull UserEntity userEntity) {
        return createJWT(userEntity.getId(), userEntity.getNickName());
    }

    public static String getUserId(String jwt) {
        JWT claims = JWTUtil.parseToken(jwt);
        return claims.getPayload("userId").toString();
    }


    public static Claims parseJWT(String jwt) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) {
        //生成密匙

        String jwt = createJWT("1", "test");
        System.out.println(jwt);
        System.out.println(getUserId(jwt));
    }

}
